package com.qjq.glasses_shopping.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qjq.glasses_shopping.mapper.AdminMapper;
import com.qjq.glasses_shopping.pojo.Admin;
import com.qjq.glasses_shopping.pojo.Permission;
import com.qjq.glasses_shopping.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@Transactional
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    @Override
    public void add(Admin admin) {
        adminMapper.insert(admin);
    }

    @Override
    public void update(Admin admin) {
        //如果密码不改保持原来的密码
        if (!StringUtils.hasText(admin.getPassword())){
            String password = adminMapper.selectById(admin.getAid()).getPassword();
            admin.setPassword(password);
        }
        adminMapper.updateById(admin);
    }

    @Override
    public void delete(Long id) {
        //先删除管理员所对应的全部角色
        adminMapper.deleteAdminAllRole(id);
        //删除管理员
        adminMapper.deleteById(id);
    }

    @Override
    public Admin findById(Long id) {
        return adminMapper.findById(id);
    }

    @Override
    public Page<Admin> search(int page, int size) {
        return adminMapper.selectPage(new Page<>(page, size), null);
    }

    @Override
    public void updateRoleToAdmin(Long aid, Long[] rids) {
        //删除角色的全部权限
        adminMapper.deleteAdminAllRole(aid);
        //添加角色的权限
        for (Long rid : rids) {
            adminMapper.addRoleToAdmin(aid, rid);
        }
    }

    @Override
    public Admin findByAdminName(String username) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        Admin admin = adminMapper.selectOne(queryWrapper);
        return admin;
    }

    @Override
    public List<Permission> findAllPermission(String username) {
        return adminMapper.findAllPermission(username);
    }
}
